<template>
    <div class="page_list">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{ $t('pageTitle.settlementCenter') }}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="5">
                        <el-form-item prop="date">
                            <el-date-picker
                                style="width:100%"
                                v-model="form.date"
                                type="datetimerange"
                                format="yyyy-MM-dd HH:mm"
                                value-format="timestamp"
                                :editable="false"
                                range-separator="-"
                                :default-time="['00:00:00', '23:59:59']"
                                :start-placeholder="$t('common.startDate')"
                                :end-placeholder="$t('common.endDate')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item prop="company"><!--公司名称-->
                            <el-select v-model="form.company" :placeholder="$t('system.companyName')" clearable style="width: 100%;">
                                <el-option v-for="company in companyList" :key="company.id" :value="company.name" :label="company.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item prop="domain"><!--用户名称-->
                            <el-select v-model="form.domain" :placeholder="$t('common.userName_')" :disabled="canChooseUserName" clearable style="width: 100%;">
                                <el-option v-for="item in domainListByCompany" :key="item.id" :value="item.domain" :label="item.domain"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                        <el-button @click="exportExcel" type="primary">{{ $t('common.export') }}</el-button>
                        <el-button v-if="balanceReminderButtonShow" @click="openBalanceWarning" type="primary">{{ $t('common.balanceAlert') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->
        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table ref="table" :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" :highlight-current-row="true">
                        <el-table-column prop="statisticsDate" :label="$t('common.date')" width="150">
                            <template slot-scope="{ row }">{{ row.statisticsDate | formatDate('yyyy-MM-dd') }}</template><!--日期-->
                        </el-table-column>
                        <el-table-column :label="$t('system.companyName')" prop="company" min-width="150"></el-table-column><!--公司名称-->
                        <el-table-column :label="$t('common.userName_')" prop="domain" min-width="150"></el-table-column><!--用户名称-->
                        <el-table-column :label="$t('common.loanSuccessAmount')" prop="loanSuccessCount" min-width="150"></el-table-column><!--放款成功笔数-->
                        <el-table-column :label="$t('common.unitPriceOfServiceCharge')" prop="loanPrice" min-width="150"><!--服务费单价-->
                            <template slot-scope="{ row }">{{ row.loanPrice | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.totalServiceCharge')" prop="loanAmount" min-width="150"><!--服务费总计-->
                            <template slot-scope="{ row }">{{ row.loanAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.numberOfRisk')" prop="rcaCount" min-width="150"></el-table-column><!--风控调用次数-->
                        <el-table-column :label="$t('common.unitPriceOfRisk')" prop="rcaPrice" min-width="150"><!--风控调用单价-->
                            <template slot-scope="{ row }">{{ row.rcaPrice | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.totalPriceOfRisk')" prop="rcaAmount" min-width="150"><!--风控调用费用总计-->
                            <template slot-scope="{ row }">{{ row.rcaAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.totalPrice')" prop="totalAmount" min-width="150"><!--费用总计-->
                            <template slot-scope="{ row }">{{ row.totalAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.balance')" prop="balanceAmount" min-width="150"><!--余额-->
                            <template slot-scope="{ row }">{{ row.balanceAmount | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column :label="$t('common.operation')" width="200">
                            <template slot-scope="scope">
                                <el-button v-if="scope.$index === 0 && modifyButtonShow" type="primary" size="small" @click="showModifyDialog(scope.row)">{{ $t('operation.modify') }}</el-button>
                                <el-button v-if="scope.$index === 0 && rechargeButtonShow" type="primary" size="small" @click="showRechargeDialog(scope.row)">{{ $t('common.recharge') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination @pageChange="pageChange" :page="page"></pagination>
                </div>
            </div>
        </div>

        <!--修改弹框-->
        <alert-dialog :title="$t('operation.modify')" :visible.sync="modifyDialog" width="416px" :dialogPosition="'center'">
            <el-form ref="modifyForm" :model="modifyForm" :rules="modifyFormRules" :label-width="language === 'zh' ? '130px' : '200px'">
                <el-form-item prop="loanPrice" :label="$t('common.unitPriceOfServiceCharge')"><!--服务费单价-->
                    <el-input v-model="modifyForm.loanPrice" type="text" :placeholder="$t('verify.plsInput')"></el-input>
                </el-form-item>
                <el-form-item prop="rcaPrice" :label="$t('common.unitPriceOfRisk')"><!--风控调用单价-->
                    <el-input v-model="modifyForm.rcaPrice" type="text" :placeholder="$t('verify.plsInput')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="goModify" type="primary">{{ $t('common.submit') }}</el-button>
                <el-button @click="modifyDialog = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </alert-dialog>

        <!--充值弹框-->
        <alert-dialog :title="$t('common.recharge')" :visible.sync="rechargeDialog" width="416px" :dialogPosition="'center'">
            <el-form ref="rechargeForm" :model="rechargeForm" :rules="rechargeFormRules" :label-width="language === 'zh' ? '130px' : '160px'">
                <el-form-item prop="amount" :label="$t('common.rechargeAmount')"><!--充值金额-->
                    <el-input  v-model="rechargeForm.amount" type="text" :placeholder="$t('verify.plsInput')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="goRecharge" type="primary">{{ $t('common.submit') }}</el-button>
                <el-button @click="rechargeDialog = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </alert-dialog><!--分配角色end-->
    </div>
</template>

<script>
    import mixin from '@/service/mixin';
    import Pagination from '@/components/pagination';
    import AlertDialog from '@/components/alert-dialog';

    let that = null;
    export default {
        name: 'collection-data',
        components: {
            Pagination,
            AlertDialog
        },
        mixins: [mixin],
        props: {
            companyList: {
                type: Array,
                default: []
            },
            domainList: {
                type: Array,
                default: []
            },
        },
        computed: {
            balanceReminderButtonShow() {
                 // 判断余额预警按钮权限
                 return this.$store.getters.checkUserAuthority('settlementCenter.balanceReminder');
             },
             modifyButtonShow() {
                 // 判断修改按钮权限
                 return this.$store.getters.checkUserAuthority('settlementCenter.modify');
             },
             rechargeButtonShow() {
                 // 判断充值按钮权限
                 return this.$store.getters.checkUserAuthority('settlementCenter.recharge');
             },
            canChooseUserName() {
                if (this.form.company) {
                    return false;
                }else {
                    return true;
                }
            },
            domainListByCompany() {
                const newResult = this.domainList.filter(item => {
                    return this.form.company === item.companyName
                })
                this.form.domain = '';
                return newResult
            },
        },
        data() {
            const checkUnitPriceServiceCharge = (rule, value, callback) => {
                if (Number(value) > 10000) {
                    return callback(new Error(this.$t('common.unitPriceRules')));/*单价不能大于10000*/
                }
                callback();
            };
            const checkUnitPriceOfRisk = (rule, value, callback) => {
                if (Number(value) > 10000) {
                    return callback(new Error(this.$t('common.unitPriceRules')));/*单价不能大于10000*/
                }
                callback();
            };
            const checkRechargeAmount = (rule, value, callback) => {
                if (Number(value) > 100000000) {
                    return callback(new Error(this.$t('common.rechargeAmountRules')));/*充值金额不能大于1亿*/
                }
                if (Number(value) < -100000000) {
                    return callback(new Error(this.$t('common.rechargeAmountRules2')));/*充值金额不能小于1亿*/
                }
                callback();
            };
            return {
                userInfo: this.$storage.get('user'),
                language: this.$storage.getLocal('language'),
                form: {
                    company: '',
                    domain: '',
                    date: ''
                },
                rules: {},
                modifyDialog: false,
                modifyForm:{
                    loanPrice: '',
                    rcaPrice: '',
                    company: '',
                    domain: '',
                },
                modifyFormRules:{
                    loanPrice: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/, message: this.$t('common.plsInputTrueAmount'), trigger: 'blur'},
                        {validator: checkUnitPriceServiceCharge, trigger: 'blur'}
                    ],
                    rcaPrice: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/, message: this.$t('common.plsInputTrueAmount'), trigger: 'blur'},
                        {validator: checkUnitPriceOfRisk, trigger: 'blur'}
                    ]
                },

                rechargeDialog: false,
                rechargeForm: {
                    amount: '',
                    company: '',
                    domain: ''
                },
                rechargeFormRules: {
                    amount: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /(?:^[-]?[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[-]?[0-9]\.[0-9](?:[0-9])?$)/, message: this.$t('common.plsInputTrueAmount'), trigger: 'blur'},
                        {validator: checkRechargeAmount, trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {
             // 获取列表数据
            getTableData(page = this.page) {
                const params = this.fillParams(page);
                this.$api.report.dailystatement(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData || [];
                        this.setPage(data.page, this.page);
                    }
                    this.tableMaxHeight = document.body.clientHeight - 210;
                });
            },
            // 搜索列表数据
            search() {
                if (!this.form.company) {
                    this.$message.error(this.$t('common.plsChooseCompany'));
                    return;
                }
                if (!this.form.domain) {
                    this.$message.error(this.$t('common.plsChooseUserName'));
                    return;
                }
                this.page.currentPage = 1;
                this.getTableData();
            },
            // 配置查询和导出参数
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    company: form.company,
                    domain: form.domain,
                    startTime: '',
                    endTime: '',
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
                Object.keys(form).forEach(key => {
                    if (typeof form[key] === 'string' && form[key]) {
                        form[key] = form[key].trim();
                        params[key] = form[key];
                    }
                });
                if (form.date) {
                    params.startTime = form.date[0];
                    params.endTime = form.date[1];
                }
                return params;
            },
            exportExcel() {
                if (!this.form.company) {
                    this.$message.error(this.$t('common.plsChooseCompany'));
                    return;
                }
                if (!this.form.domain) {
                    this.$message.error(this.$t('common.plsChooseUserName'));
                    return;
                }
                let params = this.fillParams();
                const user = this.$storage.get("user");
                const language = this.$storage.getLocal('language');
                params.language = language;
                params.token = user.token;
                const {$apiConf} = this;
                const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.report.exprotdailystatement, ["page"]);
                this.$openNewBlank(url);
            },
            showModifyDialog(row) {
                this.modifyForm.loanPrice = row.loanPrice;
                this.modifyForm.rcaPrice = row.rcaPrice;
                this.modifyForm.company = row.company;
                this.modifyForm.domain = row.domain;
                this.modifyDialog = true;
                this.$nextTick(() => {
                    this.$refs.modifyForm.clearValidate();
                });
            },
            showRechargeDialog(row) {
                this.rechargeForm.amount = '';
                this.rechargeForm.company = row.company;
                this.rechargeForm.domain = row.domain;
                this.rechargeDialog = true;
                this.$nextTick(() => {
                    this.$refs.rechargeForm.clearValidate();
                });
            },
            goModify() {
                this.$refs.modifyForm.validate(val => {
                    if (val) {
                        const params = {
                            loanPrice: this.modifyForm.loanPrice,
                            rcaPrice: this.modifyForm.rcaPrice,
                            operatorId: this.userInfo.id,
                            operatorName: this.userInfo.username,
                            company: this.modifyForm.company,
                            domain: this.modifyForm.domain
                        }
                        this.$api.report.saveunitprice(params).then(res => {
                            const {status, data, error} = res;
                            if ('1' === status && '00000000' === error) {
                                this.$message.success(this.$t('common.successfulOperation'));
                                this.getTableData();
                                this.modifyDialog = false;
                            }
                        });
                    }
                });
            },
            goRecharge() {
                this.$refs.rechargeForm.validate(val => {
                    if (val) {
                        const params = {
                            amount: this.rechargeForm.amount,
                            operatorId: this.userInfo.id,
                            operatorName: this.userInfo.username,
                            company: this.rechargeForm.company,
                            domain: this.rechargeForm.domain
                        }
                        this.$api.report.saverechargerecord(params).then(res => {
                            const {status, data, error} = res;
                            if ('1' === status && '00000000' === error) {
                                this.$message.success(this.$t('common.successfulOperation'));
                                this.getTableData();
                                this.rechargeDialog = false;
                            }
                        });
                    }
                });
            },
            //进入余额预警页面
            openBalanceWarning() {
                this.$emit('updateActiveTab', 'balanceWarning');
            }
        },
        created() {
            that = this;
            // this.getTableData();
        },
    };
</script>

<style lang="scss" scoped>
    .el-col {
        padding-left: 10px;
    }
    .el-table .cell, .el-table th > .cell {
        word-break: keep-all;
        word-wrap: break-word;
    }
    .el-tooltip__popper {
        max-width: 300px;
        word-break: break-all;
        background-color: #fff;
        box-shadow: 0px 0px 5px #ccc;
        color: #000;
    }
    .el-date-editor .el-range-separator {
        width: 35px;
    }
</style>
